﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ZHello.Algorithm
{
    public class UseLinq
    {
        /// <summary>
        /// 计算方差
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static double CalcVariance(double[] data)
        {
            if (data == null)
                throw new ArgumentNullException();
            if (data.Length == 1)
                return 0d;
            var lis = data.ToList();
            var avg = lis.Average();
            var sum = lis.Aggregate(0d, (seed, next) =>
             {
                 return Math.Pow(next, 2);
             });
            return sum / data.Length;
        }

        /// <summary>
        /// 计算标准差
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static double CalcStandDeviation(double[] data)
        {
            if (data == null)
                throw new ArgumentNullException();
            if (data.Length == 1)
                return 0d;
            var lis = data.ToList();
            var avg = lis.Average();
            var sum = lis.Aggregate(0d, (seed, next) =>
            {
                return Math.Pow(next, 2);
            });
            return Math.Sqrt(sum / data.Length);
        }
    }
}
